package com.yungu.swift.order.helper.chain;

import com.yungu.swift.order.dao.OrderMapper;
import com.yungu.swift.order.helper.model.AssignScoreParam;
import com.yungu.swift.order.helper.model.DayOrderCountVo;
import com.yungu.swift.utils.ParamUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 当天订单数量处理器
 *
 * @author : cuixiuyin
 * @date : 2019/7/8
 */
public class CurrentDayOrderCountHandler extends AssignScoreHandler {

    private OrderMapper orderMapper;

    public CurrentDayOrderCountHandler(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    @Override
    public void calculation(List<AssignScoreParam> scoreParams) {
        if (CollectionUtils.isNotEmpty(scoreParams)) {
            List<String> driverUuids = scoreParams.stream().map(AssignScoreParam::getDriverUuid).collect(Collectors.toList());
            // 统计司机当天订单量
            List<DayOrderCountVo> dayOrderCountVos = orderMapper.listDayOrderCount(driverUuids);
            Map<String, Integer> countMap = dayOrderCountVos.stream().collect(Collectors.toMap(DayOrderCountVo::getDriverUuid,
                    DayOrderCountVo::getOrderCount, (oldValue, newValue) -> newValue));
            scoreParams.forEach(scoreParam -> {
                Integer orderCount = countMap.get(scoreParam.getDriverUuid());
                scoreParam.setScore(scoreParam.getScore() + score(ParamUtil.defaultIfNull(orderCount, 0)));
            });
        }
        if (nextHandler != null) {
            nextHandler.calculation(scoreParams);
        }
    }

    /**
     * 司机订单数分值计算
     * --     1.4, 0 <= x <= 8
     * f(x) = 1.1, 8 < x <= 20
     * --     1.0, x > 20
     *
     * @param orderCount
     * @return
     */
    private Double score(Integer orderCount) {
        if (orderCount >= 0 && orderCount <= 8) {
            return 1.4;
        }
        if (orderCount > 8 && orderCount <= 20) {
            return 1.1;
        }
        return 1.0;
    }
}
